package com.panghl.service.impl;

import com.panghl.service.EmailService;
import com.panghl.utils.ConstantPropertiesUtils;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * @Author panghl
 * @Date 2021/2/3 16:53
 **/
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private FreeMarkerConfigurer configurer;

    @Autowired
    private JavaMailSender jms;

    @Override
    public boolean sendCodeByEmail(Map<String, Object> map, String sendTo) {
        MimeMessage message = null;
        try {
            message = jms.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(ConstantPropertiesUtils.USERNAME);
            // 接收地址
            helper.setTo(sendTo);
            // 标题
            helper.setSubject(ConstantPropertiesUtils.SUBJECT);
            // 处理邮件模板
            Template template = configurer.getConfiguration().getTemplate("emailTemplate.ftl");
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            helper.setText(text, true);
            jms.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
